<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>销售BI移动端</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <style>
    body {
      background: #f6f7f9;
      margin: 0;
      font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
      color: #222;
      padding-bottom: 32px;
    }
    .container {
      max-width: 480px;
      margin: 0 auto;
      padding: 12px 4px 32px 4px;
    }
    .header {
      background: #fff;
      padding: 18px 0 12px 0;
      text-align: center;
      font-size: 20px;
      font-weight: bold;
      border-radius: 0 0 18px 18px;
      margin-bottom: 18px;
      letter-spacing: 2px;
      color: #222;
      box-shadow: 0 2px 8px rgba(0,0,0,0.03);
    }
    .card {
      background: #fff;
      border-radius: 16px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.05);
      margin-bottom: 18px;
      padding: 18px 14px 14px 14px;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #222;
      margin-bottom: 6px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .segmented {
      display: flex;
      background: #f0f1f3;
      border-radius: 10px;
      overflow: hidden;
      margin-left: 8px;
    }
    .segmented button {
      flex: 1;
      border: none;
      background: none;
      padding: 6px 0;
      font-size: 14px;
      color: #222;
      cursor: pointer;
      transition: background 0.2s;
    }
    .segmented button.active {
      background: #2a7cff;
      color: #fff;
    }
    .divider {
      height: 1px;
      background: #ececec;
      margin: 10px 0;
      border: none;
    }
    .stat-row {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      font-size: 15px;
      margin: 4px 0;
    }
    .stat-label {
      color: #888;
    }
    .stat-value {
      font-weight: bold;
      color: #2a7cff;
      font-size: 18px;
    }
    .stat-value.strong {
      color: #1dbf60;
      font-size: 22px;
      font-weight: 700;
    }
    .progress-bar-bg {
      background: #ececec;
      border-radius: 8px;
      height: 10px;
      width: 100%;
      margin-top: 8px;
      margin-bottom: 6px;
      overflow: hidden;
    }
    .progress-bar {
      background: linear-gradient(90deg, #2a7cff 60%, #1dbf60 100%);
      height: 100%;
      border-radius: 8px;
      transition: width 0.4s;
    }
    .table-responsive {
      max-height: 480px;
      overflow-y: auto;
      position: relative;
      -ms-overflow-style: none; /* IE and Edge */
      scrollbar-width: none;    /* Firefox */
    }
    .table-responsive::-webkit-scrollbar {
      display: none;            /* Chrome, Safari, Opera */
    }
    .table thead th {
      position: sticky;
      top: 0;
      background: #f0f1f3;
      z-index: 2;
    }
    .table th, .table td {
      font-size: 15px;
      padding: 10px 6px;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      background: #fff;
      border-radius: 10px;
      font-size: 14px;
      margin-bottom: 8px;
    }
    th, td {
      padding: 8px 6px;
      text-align: center;
      border-bottom: 1px solid #f0f1f3;
    }
    th {
      background: #f0f1f3;
      color: #2a7cff;
      font-weight: 600;
    }
    tr:last-child td {
      border-bottom: none;
    }
    /* 隔行变色 */
    tbody tr:nth-child(even) {
      background: #e6f0fa;
    }
    tbody tr:nth-child(odd) {
      background: #fff;
    }
    .circle-progress {
      width: 48px;
      height: 48px;
      position: relative;
      display: inline-block;
      margin-right: 8px;
    }
    .circle-progress svg {
      transform: rotate(-90deg);
    }
    .circle-progress-text {
      position: absolute;
      top: 50%; left: 50%;
      transform: translate(-50%, -50%);
      font-size: 14px;
      color: #2a7cff;
      font-weight: bold;
    }
    .bar-chart {
      display: flex;
      align-items: flex-end;
      height: 70px;
      margin: 10px 0 0 0;
      gap: 8px;
    }
    .bar {
      flex: 1;
      background: #2a7cff;
      border-radius: 6px 6px 0 0;
      display: flex;
      align-items: flex-end;
      justify-content: center;
      position: relative;
    }
    .bar-label {
      font-size: 12px;
      color: #888;
      text-align: center;
      margin-top: 2px;
    }
    .bar-value {
      position: absolute;
      top: -16px;
      left: 50%;
      transform: translateX(-50%);
      font-size: 12px;
      color: #2a7cff;
      font-weight: bold;
    }
    @media (max-width: 400px) {
      .container { padding: 6px 2px 24px 2px; }
      .card { padding: 12px 6px 10px 6px; }
      .section-title { font-size: 15px; }
    }
    .table-fixed { border-radius: 10px 10px 0 0; overflow: hidden; }
    .table-scroll { border-radius: 0 0 10px 10px; }
    .table-fixed table, .table-scroll table { width: 100%; border-collapse: collapse; background: #fff; font-size: 14px; }
    .table-fixed th, .table-fixed td, .table-scroll th, .table-scroll td { padding: 8px 6px; text-align: center; border-bottom: 1px solid #f0f1f3; }
    .table-fixed th { background: #f0f1f3; color: #2a7cff; font-weight: 600; }
    .table-scroll tbody tr:nth-child(even) { background: #f9fbff; }
    .table-scroll tbody tr:nth-child(odd) { background: #fff; }
  </style>
</head>
<body>
  <div class="header">销售BI移动端</div>
  <div class="container">

    <!-- 业绩数据 -->
    <div class="card" id="performance-card">
      <div class="section-title">业绩数据</div>
      <div class="stat-row">
        <span class="stat-label">累计业绩</span>
        <span class="stat-value" id="performance-total">-</span>
      </div>
      <div class="stat-row">
        <span class="stat-label">上期业绩</span>
        <span class="stat-value" id="performance-last">-</span>
      </div>
      <div class="stat-row">
        <span class="stat-label">同比</span>
        <span class="stat-value" id="performance-compare">-</span>
      </div>
    </div>

    <!-- 渠道占比 -->
    <div class="card" id="channel-card">
      <div class="section-title">渠道占比</div>
      <div style="display: flex; flex-direction:column; align-items:center; gap: 12px;">
        <canvas id="channel-pie-chart" width="180" height="180"></canvas>
        <div id="channel-legend" style="display:flex;flex-wrap:wrap;gap:8px;justify-content:center;font-size:13px;"></div>
      </div>
    </div>

    <!-- 数据统计 -->
    <div class="card" id="statistics-card">
      <div class="section-title" style="display:flex;align-items:center;gap:10px;">
        <span>数据统计</span>
        <select id="stat-type-select" style="min-width:100px; max-width:160px; padding:6px 18px; border-radius:8px; border:1px solid #ececec; font-size:15px; display:inline-block; margin-left:10px;">
          <option value="weight">&#128230; 计费重</option>
          <option value="cbm">&#128207; CBM</option>
          <option value="customer_count">&#128202; 客户数</option>
        </select>
      </div>
      <canvas id="stat-bar-chart" height="180"></canvas>
    </div>

    <!-- 发货客户数 -->
    <div class="card" id="delivery-card">
      <div class="section-title" style="display:flex;align-items:center;gap:10px;">
        <span>发货客户数</span>
        <select id="delivery-type-select" style="min-width:80px; max-width:120px; padding:6px 14px; border-radius:8px; border:1px solid #ececec; font-size:15px; display:inline-block; margin-left:10px;">
          <option value="month">按月</option>
          <option value="week">按周</option>
        </select>
      </div>
      <canvas id="delivery-bar-chart" height="180"></canvas>
    </div>

    <!-- 客户排名 -->
    <div class="card" id="rank-card">
      <div class="section-title">客户排名</div>
      <!-- 固定表头 -->
      <div class="table-fixed">
        <table>
          <thead>
            <tr>
              <th>排名</th>
              <th>用户姓名</th>
              <th>收费重</th>
              <th>实际重量</th>
              <th>CBM</th>
              <th>泡比</th>
            </tr>
          </thead>
        </table>
      </div>
      <!-- 滚动区：所有数据 -->
      <div class="table-scroll" style="max-height:240px;overflow-y:auto;">
        <table>
          <tbody id="rank-tbody"></tbody>
          <tfoot id="rank-tfoot"></tfoot>
        </table>
      </div>
    </div>

    <!-- 风险预警 -->
    <div class="card" id="risk-card">
      <div class="section-title">风险预警</div>
      <!-- 固定表头 -->
      <div class="table-fixed">
        <table>
          <thead>
            <tr>
              <th>排名</th>
              <th>用户姓名</th>
              <th>本周业绩</th>
              <th>上周业绩</th>
              <th>同比率</th>
            </tr>
          </thead>
        </table>
      </div>
      <!-- 滚动区：所有数据 -->
      <div class="table-scroll" style="max-height:240px;overflow-y:auto;">
        <table>
          <tbody id="risk-tbody"></tbody>
        </table>
      </div>
    </div>

    <!-- 销售考核完成情况（移动端，底部） -->
    <div class="card" id="sales-kpi-card">
      <div class="section-title" style="display:flex;align-items:center;gap:10px;">
        <span>销售考核完成情况</span>
        <select id="salesKpiSelect" style="min-width:80px; max-width:120px; padding:6px 14px; border-radius:8px; border:1px solid #ececec; font-size:15px; display:inline-block; margin-left:10px;">
          <option value="weight">收费重</option>
          <option value="volume">体积</option>
        </select>
      </div>
      <div style="overflow-x:auto;">
        <table id="salesKpiTable" style="min-width:900px; border-collapse:separate; border-spacing:0;">
          <thead>
            <tr>
              <th class="fixed-col" style="position:sticky;left:0;z-index:2;background:#f0f1f3;">销售人员</th>
              <th>1月</th><th>2月</th><th>3月</th><th>4月</th><th>5月</th><th>6月</th>
              <th>7月</th><th>8月</th><th>9月</th><th>10月</th><th>11月</th><th>12月</th>
              <th>25年考核指标</th>
              <th>当前累积总数</th>
              <th class="fixed-col" style="position:sticky;right:0;z-index:2;background:#f0f1f3;">完成情况</th>
            </tr>
          </thead>
          <tbody id="salesKpiTableBody"></tbody>
        </table>
      </div>
    </div>

  </div>
  <div style="height:32px;"></div>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script>
    // 统一接口地址配置
    const API_BASE_URL = 'http://159.75.70.185:5001';
    // 业绩数据
    fetch(API_BASE_URL + '/api/performance').then(r=>r.json()).then(data=>{
      document.getElementById('performance-total').textContent = data.total || '-';
      document.getElementById('performance-last').textContent = data.last || '-';
      document.getElementById('performance-compare').textContent = (data.compare !== undefined ? data.compare + '%' : '-');
    });

    // 渠道占比 - 饼图
    let channelPieChart = null;
    function renderChannelPieChart(data) {
      const ctx = document.getElementById('channel-pie-chart').getContext('2d');
      if (channelPieChart) channelPieChart.destroy();
      // 渠道顺序
      const channelOrder = ["其他", "美国海运", "欧洲海运", "欧洲铁路", "加拿大美转加", "加拿大直航", "国际快递"];
      // 渠道颜色
      const channelColors = ["#888", "#ffb300", "#1dbf60", "#884DFF", "#e74c3c", "#2a7cff", "#00b5e2"];
      // 按顺序整理数据
      const pieData = channelOrder.map((name, idx) => {
        const found = data.find(d => d.name === name);
        return found ? found.percent : 0;
      });
      const pieLabels = channelOrder;
      // 绘制饼图
      channelPieChart = new Chart(ctx, {
        type: 'pie',
        data: {
          labels: pieLabels,
          datasets: [{
            data: pieData,
            backgroundColor: channelColors,
            borderWidth: 1
          }]
        },
        options: {
          responsive: false,
          plugins: {
            legend: { display: false },
            tooltip: {
              callbacks: {
                label: function(context) {
                  const label = context.label || '';
                  const value = context.parsed || 0;
                  return `${label}: ${value}%`;
                }
              }
            }
          }
        }
      });
      // 图例
      const legendDiv = document.getElementById('channel-legend');
      legendDiv.innerHTML = '';
      pieLabels.forEach((name, idx) => {
        legendDiv.innerHTML += `<span style="display:inline-flex;align-items:center;gap:4px;"><span style="display:inline-block;width:12px;height:12px;background:${channelColors[idx]};border-radius:2px;"></span>${name}</span>`;
      });
    }
    // 获取渠道占比数据
    fetch(API_BASE_URL + '/api/channel_ratio').then(r=>r.json()).then(data=>{
      renderChannelPieChart(data);
    });

    // 数据统计 - 条形图
    let statBarChart = null;
    let statBarData = null;
    const fixedXAxis = ["第一周", "第二周", "第三周", "第四周", "第五周"];
    function fetchStatBarData(type) {
      if (type === 'customer_count') {
        fetch(API_BASE_URL + '/api/customer_count_week')
          .then(r => r.json())
          .then(data => {
            renderStatBarChart('customer_count', data.xAxis || ["第一周", "第二周", "第三周", "第四周", "第五周"], data.data || [0,0,0,0,0]);
          })
          .catch(() => {
            renderStatBarChart('customer_count', fixedXAxis, [4, 5, 3, 6, 1]); // 本地兜底
          });
        return;
      }
      fetch(API_BASE_URL + '/api/data_statistic')
        .then(r => r.json())
        .then(data => {
          statBarData = data;
          renderStatBarChart(type);
        });
    }

    function renderStatBarChart(type, customLabels, customDataArr) {
      let labels = fixedXAxis;
      let dataArr = [];
      let label = '';
      let barColors = ['#2a7cff','#1dbf60','#ffb300','#e74c3c','#884DFF'];
      if (type === 'weight') {
        dataArr = statBarData.weight;
        label = '计费重(kg)';
      } else if (type === 'cbm') {
        dataArr = statBarData.cbm;
        label = 'CBM(m³)';
      } else if (type === 'customer_count') {
        labels = customLabels || fixedXAxis;
        dataArr = customDataArr || [0,0,0,0,0];
        label = '客户数';
      }
      // 补齐/截断数据到5周
      dataArr = (dataArr || []).slice(0, 5);
      while (dataArr.length < 5) dataArr.push(0);
      const ctx = document.getElementById('stat-bar-chart').getContext('2d');
      if (statBarChart) statBarChart.destroy();
      statBarChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: label,
            data: dataArr,
            backgroundColor: barColors,
            borderRadius: 8,
            maxBarThickness: 32
          }]
        },
        options: {
          responsive: true,
          plugins: {
            legend: { display: false },
            tooltip: { enabled: true }
          },
          scales: {
            x: {
              grid: { display: false },
              ticks: { color: '#888', font: { size: 13 } }
            },
            y: {
              beginAtZero: true,
              grid: { color: '#ececec' },
              ticks: {
                color: '#888', font: { size: 13 },
                callback: function(value) {
                  if (value >= 1000) return (value/1000).toFixed(1) + 'k';
                  return value;
                }
              }
            }
          }
        }
      });
    }

    // 修改下拉框切换事件
    document.getElementById('stat-type-select').addEventListener('change', function(e) {
      fetchStatBarData(e.target.value);
    });

    // 发货客户数 - 条形图
    let deliveryBarChart = null;
    let deliveryBarData = null;
    function renderDeliveryBarChart(type) {
      if (!deliveryBarData) return;
      let labels, dataArr;
      let barColors = ['#2a7cff','#1dbf60','#ffb300','#e74c3c','#884DFF'];
      if (type === 'week') {
        labels = ["第一周", "第二周", "第三周", "第四周", "第五周"];
        dataArr = (deliveryBarData.data || []).slice(0, 5);
        while (dataArr.length < 5) dataArr.push(0);
      } else {
        labels = (deliveryBarData.xAxis || []).slice(0, 5);
        dataArr = (deliveryBarData.data || []).slice(0, 5);
        while (labels.length < 5) labels.push('');
        while (dataArr.length < 5) dataArr.push(0);
      }
      const ctx = document.getElementById('delivery-bar-chart').getContext('2d');
      if (deliveryBarChart) deliveryBarChart.destroy();
      deliveryBarChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: '发货客户数',
            data: dataArr,
            backgroundColor: barColors,
            borderRadius: 8,
            maxBarThickness: 32
          }]
        },
        options: {
          responsive: true,
          plugins: {
            legend: { display: false },
            tooltip: { enabled: true }
          },
          scales: {
            x: {
              grid: { display: false },
              ticks: { color: '#888', font: { size: 13 } }
            },
            y: {
              beginAtZero: true,
              grid: { color: '#ececec' },
              ticks: {
                color: '#888', font: { size: 13 },
                callback: function(value) {
                  if (value >= 1000) return (value/1000).toFixed(1) + 'k';
                  return value;
                }
              }
            }
          }
        }
      });
    }
    // 获取数据并初始化
    function fetchDeliveryBarData(type) {
      const url = type === 'week' ? '/api/customer_count_week' : '/api/customer_count_month';
      fetch(API_BASE_URL + url).then(r=>r.json()).then(data=>{
        deliveryBarData = data;
        renderDeliveryBarChart(type);
      });
    }
    // 初始化默认按周
    document.getElementById('delivery-type-select').value = 'week';
    fetchDeliveryBarData('week');
    // 下拉框切换事件
    document.getElementById('delivery-type-select').addEventListener('change', function(e) {
      fetchDeliveryBarData(e.target.value);
    });

    // 客户排名
    fetch(API_BASE_URL + '/api/customer_ranking')
      .then(res => res.json())
      .then(data => {
        let html = '';
        let total = {
          '收费重': 0,
          '实际重量': 0,
          'CBM': 0,
          '泡比': 0
        };
        // 显示前20条
        const showData = data.slice(0, 20);
        showData.forEach((row, idx) => {
          html += `<tr>
            <td>${idx + 1}</td>
            <td>${row['用户姓名']}</td>
            <td>${Number(row['收费重']).toFixed(2)}</td>
            <td>${Number(row['实际重量']).toFixed(2)}</td>
            <td>${Number(row['CBM']).toFixed(2)}</td>
            <td>${Number(row['泡比']).toFixed(2)}</td>
          </tr>`;
          total['收费重'] += Number(row['收费重']);
          total['实际重量'] += Number(row['实际重量']);
          total['CBM'] += Number(row['CBM']);
          total['泡比'] += Number(row['泡比']);
        });
        document.getElementById('rank-tbody').innerHTML = html;
        // 总计行
        let totalRow = `<tr style="font-weight:bold;color:#2a4fa0;background:#f0f3fa;">
          <td colspan="2">总计：</td>
          <td>${total['收费重'].toFixed(2)}</td>
          <td>${total['实际重量'].toFixed(2)}</td>
          <td>${(total['CBM']/showData.length).toFixed(2)}</td>
          <td>${(total['泡比']/showData.length).toFixed(2)}</td>
        </tr>`;
        document.getElementById('rank-tfoot').innerHTML = totalRow;
      })
      .catch(() => {
        document.getElementById('rank-tbody').innerHTML = '<tr><td colspan="6" style="color:red;">数据加载失败</td></tr>';
        document.getElementById('rank-tfoot').innerHTML = '';
      });

    // 风险预警
    fetch(API_BASE_URL + '/api/risk_alerts').then(r=>r.json()).then(data=>{
      let html = '';
      // 显示前20条
      const showData = data.slice(0, 20);
      showData.forEach((row, idx) => {
        html += `<tr>
          <td>${row.idx}</td>
          <td>${row.name}</td>
          <td>${row.week}</td>
          <td>${row.last}</td>
          <td>${row.rate.value}</td>
        </tr>`;
      });
      document.getElementById('risk-tbody').innerHTML = html;
    });

    // 新增：销售考核数据（模拟）
    const salesKpiData = {
      weight: [
        { name: '张三', months: [1200, 1500, 1800, 2000, 2100, 2200, 2300, 2400, 2500, 2600, 2700, 2800], target: 25000 },
        { name: '李四', months: [1000, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200], target: 20000 },
        { name: '王五', months: [800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900], target: 18000 }
      ],
      volume: [
        { name: '张三', months: [120, 150, 180, 200, 210, 220, 230, 240, 250, 260, 270, 280], target: 2500 },
        { name: '李四', months: [100, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220], target: 2000 },
        { name: '王五', months: [80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190], target: 1800 }
      ]
    };
    function renderSalesKpiTable(type) {
      const tbody = document.getElementById('salesKpiTableBody');
      tbody.innerHTML = '';
      (salesKpiData[type] || []).forEach(row => {
        const total = row.months.reduce((a, b) => a + b, 0);
        const percent = row.target > 0 ? Math.min(100, (total / row.target * 100)).toFixed(1) : 0;
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td class="fixed-col" style="position:sticky;left:0;z-index:1;background:#fff;">${row.name}</td>
          ${row.months.map(m => `<td>${m}</td>`).join('')}
          <td>${row.target}</td>
          <td>${total}</td>
          <td class="fixed-col" style="position:sticky;right:0;z-index:1;background:#fff;"><span style="display:inline-block;min-width:48px;font-weight:bold;color:${percent>=100?'#1dbf60':percent>=80?'#2a7cff':'#ffb300'};">${percent}%</span></td>
        `;
        tbody.appendChild(tr);
      });
    }
    // 默认加载计费重
    fetchStatBarData('weight');
    document.getElementById('salesKpiSelect').addEventListener('change', function(e) {
      renderSalesKpiTable(e.target.value);
    });
  </script>
</body>
</html>